package yunjiao.javatutorials.guava.concurrent;

import com.google.common.util.concurrent.AbstractScheduledService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.Calendar;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 自定义
 *
 * @author yangyunjiao
 */
@Slf4j
public class CustomSchedulerService extends AbstractScheduledService {
    @Override
    protected void runOneIteration() throws Exception {
        log.info("[{}]开机执行任务：{}" , Thread.currentThread(), System.currentTimeMillis()/1000);
    }

    @Override
    protected Scheduler scheduler() {
        // 自定义调度器：周一到周五每1秒执行一次

        return new CustomScheduler() {
            @Override
            public Schedule getNextSchedule() {
                log.info("自定义调度器: {}", System.currentTimeMillis()/1000);
                Calendar now = Calendar.getInstance();
                int dayOfWeek = now.get(Calendar.DAY_OF_WEEK);

                // 周末不执行健康检查
                if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) {
                    return new Schedule(TimeUnit.HOURS.toSeconds(24), TimeUnit.SECONDS);
                }

                if (new Random().nextBoolean()) {
                    return new Schedule(1, TimeUnit.SECONDS);
                } else {
                    return new Schedule(2, TimeUnit.SECONDS);
                }
            }
        };
    }

    @Override
    protected ScheduledExecutorService executor() {
        log.info("自定义线程池");
        return Executors.newSingleThreadScheduledExecutor(
                new ThreadFactoryBuilder().setNameFormat("custom-schedule-%d").build()
        );
    }

    public static void main(String[] args) throws InterruptedException, TimeoutException {
        CustomSchedulerService service = new CustomSchedulerService();

        // 添加状态监听
        service.addListener(new Listener() {
            @Override
            public void starting() {
                log.info("服务正在启动...");
            }

            @Override
            public void running() {
                log.info("服务已运行...");
            }

            @Override
            public void stopping(State from) {
                log.info("服务正在停止（原状态：" + from + "）...");
            }

            @Override
            public void terminated(State from) {
                log.info("服务已终止（原状态：" + from + "）...");
            }

            @Override
            public void failed(State from, Throwable failure) {
                log.info("服务失败（原状态：" + from + "）：" + failure.getMessage());
            }
        }, MoreExecutors.directExecutor());

        // 启动服务（异步）
        service.startAsync();
        service.awaitRunning(); // 阻塞等待服务启动成功（进入 RUNNING 状态）
        System.out.println("服务已启动，状态：" + service.state());

        // 运行5秒后停止服务
        TimeUnit.SECONDS.sleep(7);
        service.stopAsync(); // 异步停止
        service.awaitTerminated(3, TimeUnit.SECONDS); // 阻塞等待停止完成（最多等3秒）
        System.out.println("服务已停止，状态：" + service.state());
    }
}
